package controllers

import (
	"encoding/json"
	"fmt"
	beego "github.com/beego/beego/v2/server/web"
	"live_room/cache"
	"live_room/models"
	"time"
)

type LiveController struct {
	beego.Controller
}

func (c *LiveController) Create() {
	var err error

	name := c.GetString("name")
	begin := c.GetString("begin")
	end := c.GetString("end")

	if name == "" || begin == "" || end == "" {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "参数不能为空",
		}
		c.ServeJSON()
		return
	}

	var live models.Live
	live.Name = name
	live.Begin = begin
	live.End = end

	if err = live.Create(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"code":    500,
			"message": "系统错误",
		}
		c.ServeJSON()
		return
	}

	c.Data["json"] = map[string]interface{}{
		"code":    200,
		"message": "创建成功",
	}
	c.ServeJSON()
}

func (c *LiveController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	var err error

	keyword := c.GetString("keyword")
	page, _ := c.GetInt("page")
	pageSize, _ := c.GetInt("pageSize")

	var live models.Live
	var list []models.Live

	key := fmt.Sprintf("live_list_%s_%d", keyword, page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, key).Result()

	if cacheData == "" {
		list, _ := live.List(keyword, page, pageSize)
		if len(list) != 0 {
			jsonData, _ := json.Marshal(list)
			cache.Rdb.Set(cache.Ctx, key, jsonData, time.Hour)
		}
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}

	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"status":  500,
			"message": "系统错误",
		}
		c.ServeJSON()
		return
	}

	var count int64
	models.DB.Model(&models.Live{}).Count(&count)

	c.Data["json"] = map[string]interface{}{
		"status":  200,
		"message": "查询成功",
		"data":    list,
		"count":   count,
	}
	c.ServeJSON()
}
func (c *LiveController) Del() {
	var err error
	id, _ := c.GetInt("id")
	var live models.Live
	live.ID = uint(id)

	live.GetLiveById()

	if err = live.Delete(); err != nil {
		c.Data["json"] = map[string]interface{}{
			"status":  500,
			"message": "删除失败",
		}
		c.ServeJSON()
		return
	}

	key := fmt.Sprintf("live_delId_%d", live.ID)
	cache.Rdb.Del(cache.Ctx, key)

	c.Data["json"] = map[string]interface{}{
		"status":  200,
		"message": "删除成功",
	}
	c.ServeJSON()
}
